package com.frinder.demo3;

import akka.actor.*;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import com.typesafe.config.ConfigFactory;
import scala.concurrent.duration.Duration;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by frinder on 2017/7/24.
 */
public class InboxTest extends UntypedActor {

    final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);

    public enum Msg {
        WORKING, DONE, CLOSE
    }


    @Override
    public void onReceive(Object o) throws Exception {
        logger.info("{}", o);
        Msg msg = (Msg) o;
        switch (msg) {
            case WORKING:
                getSender().tell("I am working.", getSelf());
                break;
            case DONE:
                getSender().tell("The work is done.", getSelf());
                break;
            case CLOSE:
                getSender().tell(Msg.CLOSE, getSelf());
                getContext().stop(getSelf());
                break;
            default:
                unhandled(o);
                break;
        }
    }


    public static void main(String[] args) {
        ActorSystem system = ActorSystem.create("inbox", ConfigFactory.load("akka.conf"));
        ActorRef ref = system.actorOf(Props.create(InboxTest.class), "inbox");

        Inbox inbox = Inbox.create(system);
        inbox.watch(ref);

        inbox.send(ref, Msg.WORKING);
        inbox.send(ref, Msg.DONE);
        inbox.send(ref, Msg.CLOSE);

        while (true) {
            try {
                Object message = inbox.receive(Duration.create(1, TimeUnit.SECONDS));
                if (message == Msg.CLOSE) {
                    System.out.println("inbox is closing.");
                } else if (message instanceof Terminated) {
                    System.out.println("inbox is closed.");
                    system.terminate();
                    break;
                } else {
                    System.out.println(message);
                }
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }

}
